﻿using System.Globalization;
using System.IO;
using System.Web.Helpers;
using FortuneArterial.Site.BusinessLogicLayer.LunceneSearch.Interface;
using FortuneArterial.Site.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lucene.Net.Documents;

namespace FortuneArterial.Site.Laboratory.Models
{
    public class FileEntity
        : BaseEntity, ILuceneEntity
    {
        public string DirName { get; set; }
        public string FileName { get; set; }
        public string FileType { get; set; }
        public long FileSize { get; set; }

        public FileEntity()
        {

        }

        public FileEntity(string path)
            : this()
        {
            this.ID = path.GetHashCode().ToString();
            this.DirName = Path.GetDirectoryName(path);
            this.FileName = Path.GetFileName(path);
            this.FileType = Path.GetExtension(path);
            try
            {
                var fileInfo = new FileInfo(path);
                this.FileSize = fileInfo.Length;
            }
            catch (PathTooLongException ex)
            {
            }
        }

        public virtual Document ToDocument()
        {
            var doc = new Document();

            doc.Add(new Field("ID", this.ID, Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field("DirName", this.FileName, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("FileName", this.FileName, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("FileType", this.FileType, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("FileSize", this.FileSize.ToString(), Field.Store.YES, Field.Index.ANALYZED));

            return doc;
        }

        public virtual void FromDocument(Document doc)
        {
            this.ID = doc.Get("ID");
            this.DirName = doc.Get("DirName");
            this.FileName = doc.Get("FileName");
            this.FileType = doc.Get("FileType");
            this.FileSize = long.Parse(doc.Get("FileSize"));
        }
    }
}